<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="70%"
      draggable
      @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <!--      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>-->
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button v-if="!props.isReadonly" type="success" plain @click="handleAdd">
            <i-ep-plus/>
            新增
          </el-button
          >
        </template>
        <div class="formTable">
          <el-table
              :data="inputConfig.colomList"
              style="width: 100%"
              border
          >
            <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
            />

            <el-table-column label="字段名" props="fieldDesc">
              <template #default="{$index,row}">
                <el-input v-model="row.colomName" placeholder="请输入字段名"
                          clearable/>
              </template>
            </el-table-column>

            <el-table-column label="字段描述" props="fieldDesc">
              <template #default="{$index,row}">
                <el-input v-model="row.remarks" placeholder="请输入字段描述"
                          clearable/>
              </template>
            </el-table-column>

            <el-table-column label="字段类型" props="fieldDesc">
              <template #default="{$index,row}">
                <el-input v-model="row.colomNameType" placeholder="请输入字段类型"
                          clearable/>
              </template>
            </el-table-column>

            <el-table-column label="字段样例" props="fieldDesc">
              <template #default="{$index,row}">
                <el-input v-model="row.colomSample" placeholder="请输入字段样例"
                          clearable/>
              </template>
            </el-table-column>


            <el-table-column fixed="right" align="center" label="操作" width="120">
              <template #default="scope">
                <el-button :disabled="inputConfig.colomList.length < 2" type="danger" link
                           @click.stop="handleDelete(scope.$index)">
                  <i-ep-delete/>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!props.isReadonly" type="primary" :loading="loading" @click="handleSubmit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import {useDictStoreHook} from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "DMPREALTIMECOLLECTERINPUT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
    () => props.visible,
    (newVal: boolean) => {
      visibleDialog.value = newVal;
    }
);

const wareList = ref([])
let tableList = ref([])

const rules = reactive({
  collecterCode: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  collecterName: [
    {min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur"}
  ],
  interfaceType: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  isInsert: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  isUpdate: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  isBatch: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  collecterScript: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  remarks: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  enabled: [],
  apiUrl: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  messageType: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
});


const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  collecterCode: "",
  collecterName: "",
  interfaceType: "",
  isInsert: "",
  isUpdate: "",
  isInsertStr: "",
  isUpdateStr: "",
  isBatch: "",
  collecterScript: "",
  inputConfig: "",
  outputConfig: "",
  remarks: "",
  enabled: "",
  deleted: "",
  createdUserId: "",
  createTime: "",
  lastUpdatedUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserName: "",
  apiUrl: "",
  messageType: "",
});


let inputConfig = reactive({
  warehouseId: "",
  tableNmae: "",
  colomList: [{
    colomName: "",
    colomNameType: "",
    remarks: "",
    colomSample: "",
  }
  ]
});

const details = {
  colomName: "",
  colomNameType: "",
  remarks: "",
  colomSample: "",
};

watch(
    () => props.data,
    (newVal: any) => {
      formData.id = ""
      if (newVal?.id) {
        const {
          id,
          collecterCode,
          collecterName,
          interfaceType,
          isInsert,
          isInsertStr,
          isUpdateStr,
          isUpdate,
          isBatch,
          collecterScript,
          inputConfig,
          outputConfig,
          remarks,
          enabled,
          deleted,
          createdUserId,
          createTime,
          lastUpdatedUserId,
          createdUserName,
          lastUpdateTime,
          lastUpdatedUserName,
          apiUrl,
          messageType,
        } = newVal;
        Object.assign(formData, {
          id,
          collecterCode,
          collecterName,
          interfaceType,
          isInsert,
          isInsertStr,
          isUpdateStr,
          isUpdate,
          isBatch,
          collecterScript,
          inputConfig,
          outputConfig,
          remarks,
          enabled,
          deleted,
          createdUserId,
          createTime,
          lastUpdatedUserId,
          createdUserName,
          lastUpdateTime,
          lastUpdatedUserName,
          apiUrl,
          messageType,
        });
      }
      if (newVal?.inputConfig) {
        let data = JSON.parse(newVal?.inputConfig);
        inputConfig.warehouseId = data.warehouseId
        inputConfig.tableNmae = data.tableNmae
        inputConfig.colomList = data.colomList
      }
    }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = ""
  formData.collecterCode = ""
  formData.collecterName = ""
  formData.interfaceType = ""
  formData.isInsert = ""
  formData.isInsertStr = ""
  formData.isUpdateStr = ""
  formData.isUpdate = ""
  formData.isBatch = ""
  formData.collecterScript = ""
  formData.inputConfig = ""
  formData.outputConfig = ""
  formData.remarks = ""
  formData.enabled = ""
  formData.deleted = ""
  formData.createdUserId = ""
  formData.createTime = ""
  formData.lastUpdatedUserId = ""
  formData.createdUserName = ""
  formData.lastUpdateTime = ""
  formData.lastUpdatedUserName = ""
  formData.apiUrl = ""
  formData.messageType = ""

  inputConfig.colomList = [JSON.parse(JSON.stringify(details))]
  inputConfig.warehouseId = ""
  inputConfig.tableNmae = ""
}

const loading = ref(false);

/** 数据采集器保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;

      formData.isUpdate = formData.isUpdateStr ? 1 : 0;
      formData.isInsert = formData.isInsertStr ? 1 : 0;
      formData.inputConfig = JSON.stringify(inputConfig)
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpAdmin/dmprealtimecollecter/updateInputConfig",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  inputConfig.colomList.push(sondata);
};

/** 删除行 */
const handleDelete = (index: any) => {
  inputConfig.colomList.splice(index, 1);
};

</script>
